package 生产者;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

public class KafkaTransactionalProducer {

    public static void main(String[] args) {
        // 配置生产者的属性
        Properties props = new Properties();
        // Kafka集群地址
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "114.251.235.19:9092");
        // 启用幂等性和事务
        props.put("enable.idempotence", "true");
        props.put("transactional.id", "my-transactional-id"); // 必须为事务指定一个唯一的ID
        // 序列化器配置
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        KafkaProducer<String, String> producer = new KafkaProducer<>(props);

        try {
            // 初始化事务
            producer.initTransactions();

            try {
                // 开始一个新的事务
                producer.beginTransaction();

                // 创建并发送一条或多条消息
                ProducerRecord<String, String> record = new ProducerRecord<>("your_topic_name", "key1", "value1");
                producer.send(record);

                // 假设这里有一些业务逻辑可能会抛出异常
                // 如果发生异常，则调用producer.abortTransaction()来撤销事务

                // 提交事务
                producer.commitTransaction();
            } catch (Exception e) {
                // 如果发生异常，撤销事务
                producer.abortTransaction();
                System.out.println("Transaction is aborted due to exception: " + e.getMessage());
            }
        } finally {
            // 关闭生产者
            producer.close();
        }
    }
}